package com.laicunba.service.impl.udcredit;

import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.laicunba.pojo.RegistryDO;
import com.laicunba.service.RegistryService;
import com.laicunba.service.UdcreditService;

@Service
public class UdcreditServiceImpl implements UdcreditService {
	private static final Logger LOG = Logger.getLogger(UdcreditServiceImpl.class);

	@Autowired
	private RegistryService registryService;

	@Override
	public boolean isYangmao(String mobile) {
		Map<String, String> param = ParameterFactory.getShimingParameterMap(mobile);
		AntifraudRequest request = new AntifraudRequest();
		request.setPartnerCode(DemoConfig.PARTNER_CODE);
		request.setNonceStr(RandomStringUtils.randomNumeric(32));
		request.setStrategyCode(DemoConfig.SHIMING_STRATEGY_CODE);
		request.setScenarioCode(DemoConfig.SHIMING_SENARIO_CODE);
		request.setPackageStr(SignatureHelper.generateSignedPackageStr(param));
		request.setSignature(SignatureHelper.generateSignatureFromRequest(DemoConfig.SECRET_KEY, request));
		System.out.println(request);

		HttpRequestSimple httpRequestSimple = new HttpRequestSimple();
		String response = httpRequestSimple.postSendHttp(DemoConfig.SERVICE_URL, request.toString());
		LOG.info(mobile + " : " + response);
		try {
			JSONObject json = (JSONObject) new JSONParser().parse(response);
			return "9999".equalsIgnoreCase((String) json.get("retCode"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean isOpen() {
		RegistryDO regedit = registryService.get(RegistryDO.class, "sys.udcredit.check");
		return regedit != null;
	}
}
